package com.siwei.mes.service.experiment.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.CheckQuickConfig;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.system.TemperatureAndHumidity;
import com.siwei.mes.enums.CheckEnum;
import com.siwei.mes.enums.RoleEnum;
import com.siwei.mes.mapper.experiment.CheckBatchConfigMapper;
import com.siwei.mes.mapper.experiment.CheckQuickConfigMapper;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.service.experiment.ExperimentDetailService;
import com.siwei.mes.service.system.AuthService;
import com.siwei.mes.service.system.TemperatureAndHumidityService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 试验台账json详情(ExperimentDetail)表服务实现类
 *
 * @author linzi
 * @since 2023-12-27 23:30:45
 */
@Service
public class ExperimentDetailServiceImpl implements ExperimentDetailService {
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private AuthService authService;
    @Resource
    private CheckQuickConfigMapper checkQuickConfigMapper;
    @Resource
    private CheckBatchConfigMapper checkBatchConfigMapper;
    @Resource
    private TemperatureAndHumidityService temperatureAndHumidityService;

    @Override
    public Long create(ExperimentDetail entity) {
        entity.init(true);
        experimentDetailMapper.insertSelective(entity);
        return entity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ExperimentDetail entity) {
        if (CheckEnum.BATCH.getCode().equals(entity.getCheckType())) {
            List<String> rolePermission = new ArrayList<>();
            rolePermission.add(RoleEnum.TESTER.getCode());
            rolePermission.add(RoleEnum.TESTER_DIRECTOR.getCode());
            rolePermission.add(RoleEnum.CHIEF_ENGINEER.getCode());
            assertTrue(!rolePermission.contains(authService.getLoginUserRole()), "您暂无权限操作");
        }
        ExperimentDetail experimentDetail = experimentDetailMapper.selectByPrimaryKey(entity.getId());
        assertTrue(experimentDetail == null, "试验台账json详情信息不存在");
        experimentDetail.init(false);
        experimentDetailMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void delete(Long id) {
        ExperimentDetail experimentDetail = experimentDetailMapper.selectByPrimaryKey(id);
        assertTrue(experimentDetail == null, "试验台账json详情信息不存在");
        experimentDetailMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<ExperimentDetail> getPage(PageQuery<ExperimentDetail, ExperimentDetail> query) {
        ExperimentDetail searchParam = query.getParams();
        return PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> experimentDetailMapper.getList(searchParam));
    }

    @Override
    public ExperimentDetail loadById(Long id) {
        return experimentDetailMapper.loadById(id);
    }

    @Override
    public List<ExperimentDetail> getAll(ExperimentDetail entity) {
        return experimentDetailMapper.getList(entity);
    }

    @Override
    public Map<Long, String> getTestProjectNameMap(List<Long> experimentIdList) {
        Map<Long, String> map = new HashMap<>();
        List<ExperimentDetail> list = experimentDetailMapper.getList(new ExperimentDetail().setExperimentIdList(experimentIdList));
        for (ExperimentDetail detail : list) {
            Long experimentId = detail.getExperimentId();
            String testProjectName = detail.getTestProjectName();
            if (StringUtils.isBlank(testProjectName)) {
                continue;
            }

            if (map.containsKey(experimentId)) {
                String testProjectNameStr = map.get(experimentId);
                map.put(experimentId, testProjectNameStr + "," + testProjectName);
            } else {
                map.put(experimentId, testProjectName);
            }
        }
        return map;
    }

    /**
     * 组装其它信息  试验依据、判断依据、仪器设备、最后一条含水率配置
     *
     * @param experimentDetail 试验委托信息
     * @param testProjectCode 试验项目
     * @param testProjectCode 试验材料类型
     */
    @Override
    public void payloadOtherInfo(ExperimentDetail experimentDetail, String testProjectCode,Integer projectCategory) {
        Integer checkType = experimentDetail.getCheckType();//委托类型 1-快检 2-批检
        Set<String> experimentGistList = new HashSet<>();//试验依据集合
        Set<String> judgeGistList = new HashSet<>();//判断依据集合

        /**这里根据试验项目去查询配置的试验依据和判断依据  检查类型 1-快检 2-批检*/
        Set<String> equipmentNos = new LinkedHashSet();
        if (testProjectCode != null && !testProjectCode.isEmpty()) {
            if (CheckEnum.QUICK.getCode().equals(checkType)) {
                List<CheckQuickConfig> list = checkQuickConfigMapper.getList(new CheckQuickConfig().setTestProjectCode(testProjectCode).setProjectCategory(projectCategory));
                for (CheckQuickConfig config : list) {
                    if (StringUtils.isNotBlank(config.getExperimentGist())) {
                        List<String> experimentGists = Arrays.stream(config.getExperimentGist().split(";"))
                                .collect(Collectors.toList());
                        experimentGistList.addAll(experimentGists);
                    }
                    if (StringUtils.isNotBlank(config.getJudgeGist())) {
                        List<String> judgeGists = Arrays.stream(config.getJudgeGist().split(";"))
                                .collect(Collectors.toList());
                        judgeGistList.addAll(judgeGists);
                    }
                    if(StringUtils.isNotBlank(config.getEquipmentNo())){
                        equipmentNos.addAll(Arrays.stream(config.getEquipmentNo().split(";"))
                                .map(String::trim)
                                .filter(part -> !part.isEmpty())
                                .collect(Collectors.toList()));
                    }
                }
            } else if (CheckEnum.BATCH.getCode().equals(checkType)) {
                List<CheckBatchConfig> list = checkBatchConfigMapper.getList(new CheckBatchConfig().setTestProjectCode(testProjectCode).setProjectCategory(projectCategory));
                for (CheckBatchConfig config : list) {
                    if (StringUtils.isNotBlank(config.getExperimentGist())) {
                        List<String> experimentGists = Arrays.stream(config.getExperimentGist().split(";"))
                                .collect(Collectors.toList());
                        experimentGistList.addAll(experimentGists);
                    }
                    if (StringUtils.isNotBlank(config.getJudgeGist())) {
                        List<String> judgeGists = Arrays.stream(config.getJudgeGist().split(";"))
                                .collect(Collectors.toList());
                        judgeGistList.addAll(judgeGists);
                    }
                    if(StringUtils.isNotBlank(config.getEquipmentNo())){
                        equipmentNos.addAll(Arrays.stream(config.getEquipmentNo().split(";"))
                                .map(String::trim)
                                .filter(part -> !part.isEmpty())
                                .collect(Collectors.toList()));
                    }
                }
            }
        }

        /**试验依据*/
        if (!experimentGistList.isEmpty()) {
            String experimentGist = experimentGistList.stream().map(String::valueOf).collect(Collectors.joining(";"));
            experimentDetail.setExperimentGist(experimentGist);
        }
        /**判断依据*/
        if (!judgeGistList.isEmpty()) {
            String judgeGist = judgeGistList.stream().map(String::valueOf).collect(Collectors.joining(";"));
            experimentDetail.setJudgeGist(judgeGist);
        }

        /**获取仪器设备*/
        /*MaterialsEnum materialsEnum = MaterialsEnum.selectByCode(projectCategory);
        if (materialsEnum != null) {
            List<Equipment> equipmentInfoList = equipmentService.getEquipmentInfo(materialsEnum.getTestProjectType());
            if (!equipmentInfoList.isEmpty()) {
                String equipment = equipmentInfoList.stream().map(Equipment::getEquipmentName).collect(Collectors.joining(","));
                experimentDetail.setEquipment(equipment);
            }
        }*/
        if(CollectionUtil.isNotEmpty(equipmentNos)){
            experimentDetail.setEquipment(String.join(";",equipmentNos));
        }
        /**获取最后一条含水率配置*/
        TemperatureAndHumidity lastInfo = temperatureAndHumidityService.getLastInfo(new TemperatureAndHumidity());
        if (lastInfo != null) {
            experimentDetail.setTemperature(lastInfo.getTemperature());
            experimentDetail.setHumidness(lastInfo.getHumidness());
        }
    }
}
